<?php
class CategoryController extends AuthController{
	//栏目模型
	private $db;
	//栏目缓存
	private $category;
	//商品类型缓存
	private $goodsType;
	//栏目id
	private $cid;
	//构造函数
	public function __init(){
		$this->db= K('Category');
		//读取缓存
		$this->category = S('category');//栏目缓存
		$this->goodsType = S('goods_type');//商品类型
		$this->cid=Q('cid',0,'intval');
		if($this->cid && !isset($this->category[$this->cid])){
			$this->error('栏目不存在');
		}
	}
	/**
	 * 栏目列表
	 * @return [type] [description]
	 */
	public function index(){
		int_to_string($this->category,array('is_show'=>array(0=>'隐藏',1=>'显示')));
		$this->assign('data',$this->category);
		$this->display();
	}
	/**
	 * 添加栏目
	 */
	public function add(){
		if(IS_POST){
			if($this->db->addCategory()){
				$this->success('添加成功','index');
			}else{
				$this->error($this->db->error);
			}
		}else{//分配栏目
			$this->assign("category",$this->category);
			//分配商品类型		
			$this->assign("goodsType",$this->goodsType);	
			// p($this->goodsType);die;
			$this->display();
		}
	}

	//修改栏目
	public function edit(){
		if(IS_POST){
			if($this->db->editCategory()){
				$this->success('修改成功','index');
			}else{
				$this->error($this->db->error);
			}
		}else{ 
			// $cid =Q('get.cid',0,'intval');
			//取当前编辑栏目数据
			// $field= $this->db->find($cid);
			$field= $this->category[$this->cid];
			$this->assign('field',$field);	
			//取所有栏目数据
			$category = $this->category;
			foreach($category as $id=>$cat){
				//当前父栏目设置 selected属性
				$category[$id]['selected']=$cat['cid']==$field['pid']?" selected='' ":'';			
				//子栏目设置disabled属性为不能被选中  自身也不能选择
				// Data::isChild() 判断是否为子栏目
				// 数组,子id,父栏目id
				$category[$id]['disabled']=Data::isChild($category,$cat['cid'],$field['cid']) || $cat['cid']==$field['cid']?
					" disabled='' ":'';
			}
			// p($category);
			$this->assign('category',$category);
			//分配商品类型		
			$this->assign("goodsType",$this->goodsType);
			$this->display();
		}
	}

	//删除栏目
	public function del(){
		if($this->db->delCategory()){
			$this->success('删除栏目成功');
		}else{
			$this->error('删除失败');
		}
	}

	//更新缓存
	public function updateCache(){
		if($this->db->updateCache()){
			$this->success('更新成功','index');
		}else{
			$this->error('更新失败','index');
		}
	}

}//商品栏目控制器类结束